package  com.sat.common.network;

import com.sat.common.utils.OkHttpUtils
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitUtils {
    private lateinit var mParams: RetrofitParams;

    fun getRetrofit(params: RetrofitParams): Retrofit {
        mParams = params;
        return Retrofit.Builder().baseUrl(params.url)
            .addConverterFactory(GsonConverterFactory.create())
            .client(getOkHttpClient())
            .build()
    }

    private fun getOkHttpClient(): OkHttpClient {
        return OkHttpUtils.newBuilder().apply {
            addInterceptor(HttpParamsInterceptor())
            mParams.customInterceptor?.run {
                addInterceptor(this)
            }
            addInterceptor(
                HttpLoggingInterceptor(HttpLoggingInterceptor.Logger() { message ->
                    mParams.logListener?.log(message)
                }).setLevel(HttpLoggingInterceptor.Level.BODY)
            )

        }.build();

    }


    /**
     * 统一设置接口公共参数
     */
    class HttpParamsInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val original = chain.request();
            val builder = original.url.newBuilder()
            mParams.globalParamsListener?.onGlobalParamsSetting(builder)
            val headerBuilder = original.newBuilder();
            mParams.globalParamsListener?.onHeaderParamsSetting(headerBuilder)
            val httpUrl: HttpUrl = builder.build();

            val request = headerBuilder
                .method(original.method, original.body)
                .url(httpUrl)
                .build();

            val response: Response = chain.proceed(request)
            return if (mParams.dataResponseListener != null) {
                val mediaType = response.body?.contentType()
                val content = response.body?.string()
                mParams.dataResponseListener?.onHandleResponse(content);
                response.newBuilder()
                    .body(ResponseBody.create(mediaType, content ?: ""))
                    .build();
            } else {
                response
            }

        }
    }
}
